---
title: "R Notebook"
output: html_notebook
---


```{r}

rm(list=ls())
if (!require("pacman")) install.packages("pacman")
pacman::p_load(tidyverse, rio, scales)

#dir = "C:/Users/pedro/Dropbox (Personal)/Sleep Data/01. Main Study"
path.inp = file.path(dir, "Datasets")
path.out = file.path(dir, "Output/Appendix/Figures")

# My theme
mytheme = theme_bw() +
  theme(panel.grid.major.x = element_blank(),
        panel.grid.minor.x = element_blank(),
        panel.grid.minor.y = element_blank(),
        panel.border = element_blank(),
        axis.line = element_line(color = "black"),
        text =  element_text(size = 12),
        axis.text = element_text(color = "black"))

# Import data
df.raw = import(file.path(path.inp, "firststage_dataset.dta")) %>% as_tibble()

```

Edits to data set

```{r}

df = df.raw %>% 
  filter(post_treatment == 1 & at_present_check == 1) %>% 
  select(pid, day_in_study, nap_time_mins, treat_nap)  %>% 
  filter(treat_nap == 1) %>% 
  filter(day_in_study < 28) %>% 
  mutate(dum_sleep = 1*(nap_time_mins > 0))

```


Graph

```{r}

df  %>% 
  ggplot(aes(x = nap_time_mins, y = ..count../sum(..count..))) +
  mytheme +
  geom_histogram(color = "white", fill = rgb(62, 97, 128, max = 255)) +
  labs(y = "Percentage",
       x = "Minutes napping") +
  scale_y_continuous(expand = c(0,0), label = percent_format(accuracy = 1)) +
  geom_vline(xintercept = round(mean(df$nap_time_mins, na.rm = T), 2), color = "red", lty = 2, size = 1) +
  annotate(geom = "text", label = paste0("Mean: ", round(mean(df$nap_time_mins, na.rm = T), 1)),
           x = round(mean(df$nap_time_mins, na.rm = T), 1) - 2.3, y = .11, color = "red")
  
ggsave(file.path(path.out, "FigureA2_hist_mins_naps.pdf"))
  
```


Stats for the paper

```{r}

# Probability of sleeping actigraph

df %>% 
  group_by(dum_sleep) %>% 
  summarise(prob = n()/nrow(df),
            mean = mean(nap_time_mins, na.rm = T))
  
df$nap_time_mins %>% median()

```



